package socket;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/*客户端
java.net.socket 套接字
socket封装了tcp 协议的通讯，使用它可以和远程计算机上的服务端程序建立连接
并基于两条流进行IO操作完成对应的数据交互
 */
public class Client {
    private Socket socket;
    public Client() {

        try {
            System.out.println("准备连接");
            socket = new Socket("localhost",8088);
            System.out.println("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            OutputStream out = socket.getOutputStream();
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入内容");
            while (true){
                String s = scanner.nextLine();
                if ("exit".equals(s)){
                    break;
                }
                byte[] data = s.getBytes(StandardCharsets.UTF_8);
                out.write(data.length);
                out.write(data);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}

